<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

// 检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

$currentUser = $_SESSION['username'];
$toUser = $_POST['to_user'] ?? '';

if (empty($toUser)) {
    die('目标用户不能为空！');
}

// 检查是否已经发送过好友请求
$requestsFile = __DIR__ . "/user/$toUser/requests.json";
$requests = ensureFile($requestsFile);

foreach ($requests as $req) {
    if ($req['from'] === $currentUser) {
        die('您已向该用户发送过好友请求，请等待对方处理！');
    }
}

// 添加好友请求
$requests[] = [
    'from' => $currentUser,
    'timestamp' => date('Y-m-d H:i:s')
];
file_put_contents($requestsFile, json_encode($requests));

// 系统消息通知
$systemMessagesFile = __DIR__ . "/user/$toUser/system_messages.json";
$systemMessages = ensureFile($systemMessagesFile);
$systemMessages[] = [
    'type' => 'friend_request',
    'from' => $currentUser,
    'content' => "$currentUser 请求添加您为好友。",
    'timestamp' => date('Y-m-d H:i:s')
];
file_put_contents($systemMessagesFile, json_encode($systemMessages));

// 响应
echo "好友请求已发送！";